014. Longest Common Prefix[E]

问题

Write a function to find the longest common prefix string amongst an array of strings.

Subscribe to see which companies asked this question

思路

这个没啥思路的,怎么都要两重循环,因为是最长公共子串,随便找一个(一般是第一个作为基准),然后拿拿的首部慢慢去匹配后面的字符串就行了。

  1. public class Solution {
  2. public String longestCommonPrefix(String[] strs) {
  3. String s = "";
  4. if(strs.length == 0)
  5. return "";
  6. for(int i = 0; i < strs[0].length();i++)
  7. {
  8. char c = strs[0].charAt(i);
  9. for(int j = 1;j < strs.length;j++)
  10. {
  11. if(i >= strs[j].length() || strs[j].charAt(i) != c)
  12. return s;
  13. }
  14. s += c;
  15. }
  16. return s;
  17. }
  18. }